import React, { PureComponent } from 'react';
import { connect } from 'dva';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import styles from '@/components/common/PateoTable/TableList.less';
import { Card, Button, message,  } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import AddModal from './addModal';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { getDicByKey,} from '@/support/common';
import PropTypes from 'prop-types';

const mapStateToProps = (state: any) => {
  return {
    goodAttribute: state.goodAttribute,
    loading: state.loading.effects['goodAttribute/postFetchPage'],
    menu:state.menu,
  };
};

class goodAttribute extends PureComponent<any, any> {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.any,
  };
  state = {
    rightQuery: {},
    pagination: {
      current: 1,
      pageSize: 10,
    },
    addVisible: false,
    isAdd:true,
    record:{},
    goodsTypeOptions:[],
  };
  searchRef = null;

  componentDidMount() {
    this.handleFlushPage();
    this.getGoodsType();
  }
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'goodAttribute/initData',
    });
  }
  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { rightQuery, pagination } = this.state;
    dispatch({
      type: 'goodAttribute/postFetchPage',
      payload: { url: '/optshop/base/subsidiary/attribute/search', ...rightQuery, ...pagination },
    });
  };
  //获取商品类型新阿拉数据
  getGoodsType=()=>{
    this.props.dispatch({
      type: 'goodAttribute/getDataWithRes',
      payload: { url: '/optshop/base/goodstype/query/drop/list',},
      callback: (res:any) => {
        this.setState({ 
          goodsTypeOptions: res?.data?.list?.map((item:any)=>{
            return {
              label: item.goodsTypeName,
              value: item.goodsTypeId
            }
           }),
        });
       }
    })
  }
  //新增
  handleAdd=()=>{
    this.setState({
        addVisible: true,
        isAdd:true,
      });
  }
  closeAddModal = () => {
    this.setState({
      addVisible: false,
      isAdd:true,
      record: {}
    });
    this.handleFlushPage();
  };
  handleEdit = (record:any) =>{
    this.setState({
        addVisible: true,
        isAdd:false,
        record: record,
      });
  }
   //删除
   handleDeleteDate=(record:any)=>{
     const { dispatch} = this.props;
     dispatch({
       type: 'goodAttribute/getDataWithRes',
       payload: {
         url: '/optshop/base/subsidiary/attribute/delete',
         sid: record.sid,
       },
       callback: (response: any) => {
         if (response.statusCode === '0') {
               message.success('删除成功') ;
           this.handleFlushPage();
         }
       },
     });
     }
  render() {
    const { rightQuery,addVisible,isAdd,record,goodsTypeOptions} = this.state;
    const {
      loading,
      location: { pathname = '/' },
       goodAttribute: {
        pageData: { list, pagination },
      },
    } = this.props;
    const { menu: { permissions }} = this.props;
    const isAddAuth = permissions.includes('/goodsManager/goodsAttribute/goodsAttribute_doAdd');
    const searchItems = [
      {
        type: 'input',
        title: `属性名称`,
        key: 'skuAttributeName',
      },
      {
        type: 'input',
        title: `属性代码`,
        key: 'skuAttributeCode',
      },
      {
        type: 'select',
        title: `商品类型`,
        key: 'goodsTypeId',
        selectOptions: goodsTypeOptions,
      },
    ];

    const columns = [
      {
        title: `品牌`,
        dataIndex: 'brandName',
      },
      {
        title: `属性名称`,
        dataIndex: 'skuAttributeName',
      },
      {
        title: `属性编码`,
        dataIndex: 'skuAttributeCode',
      },
      {
        title: `单位`,
        dataIndex: 'unit',
        render: text => {
          if (text == null) {
            return '';
          }
          return getDicByKey(this.context.dicData, `unit`, text + '');
        },
      },
      {
        title: `商品类型`,
        dataIndex: 'goodsTypeName',
      },
      {
        title: `创建人`,
        dataIndex: 'createBy',
      },
      {
        title: `创建时间`,
        dataIndex: 'createTime',
      },
      {
        title: `修改人`,
        dataIndex: 'updateBy',
      },
      {
        title: `修改时间`,
        dataIndex: 'updateTime',
      },
      {
        title: `操作`,
        dataIndex: '操作',
        fixed: 'right',
        width: 100,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'goodsAttribute_doEdit',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '删除',
              key: 'delete',
              auth: 'goodsAttribute_doDel',
              Popconfirm: true,
              message: '是否确认删除？',
              onConfirm: () => this.handleDeleteDate(record),
            }
          ];
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        }
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => <span>共&nbsp;{!pagination ? 0 : pagination.total}&nbsp;条</span>,
    };
    const tableProps = {
      columns:columns,
      dataSource: [...(list || [])],
      loading,
      rowKey: (record: any) => record.sid,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    return (
      <div>
        <Card>
          <PateoSearchForm
            onRef={(ref :any) => (this.searchRef = ref)}
            searchItems={searchItems}
            fetchParams={{ type: 'goodAttribute/postFetchPage', url: '/optshop/base/subsidiary/attribute/search' }}
            saveFormValues={(val: any) =>
              this.setState({ rightQuery: Object.assign(rightQuery, val) })
            }
            handleFormReset={() => this.setState({ 
            rightQuery: {},
             pagination: {
              current: 1,
              pageSize: 10,
            }, })}
            handleFieldsValue={(val: any) => {
              const { pagination } = this.state;
              return {
                ...val,
                ...pagination,
              };
            }}
          />
        </Card>
        <Card className={styles.standardTable}>
        {isAddAuth && (
        <div style={{marginBottom: '10px'}}>
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => this.handleAdd()}
          >
            新增
          </Button>
          </div>
        )}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'goodAttribute/postFetchPage', url: '/optshop/base/subsidiary/attribute/search'}}
            formValues={rightQuery}
          />
        </Card>
        <AddModal
          modalVisible={addVisible}
          closeModal={this.closeAddModal}
          isAdd={isAdd}
          record={record}
          dispatch={this.props.dispatch}
        />
      </div>
    );
  }
}

export default connect(mapStateToProps)(goodAttribute);
